<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/7/22
 * Time: 9:37
 */

namespace app\logic\cron;


use app\common\lib\Common;
use app\common\lib\Oceanengine;
use app\common\lib\TencentCos;
use app\logic\BaseLogic;
use app\model\novel\NovelSpreadModel;
use app\model\oceanengine\OceanengineAcceptedTaskListModel;
use app\model\oceanengine\OceanengineNotacceptedTaskListModel;
use support\Cache;
use support\Db;

class OceanengineLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
//        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return  new self();
    }

    public function getNovelTaskList()
    {
        //todo 1 获取未参与任务列表
        $this->getNotAcceptedTaskList();

        //todo 2 获取参与任务列表
        $this->getAcceptedTaskList();

        //todo 3 接受新任务
        $apps = [
            ['appid'=>'tt4d613bdcd2523d8b01','fix_name'=>'小说冰雨','business_id'=>100,'platform'=>1]
        ];
        foreach ($apps as $app){
           $this->acceptedTask($app);
        }

        //接受完任务，没那么快就可以拿到列表数据，这里延迟60秒看看
        sleep(60);

        //todo 4 再一次获取参与任务列表
        $this->getAcceptedTaskList();

        //todo 5 更新和插入小说数据
        foreach($apps as $app){
            //参与任务列表
            $where = [
                'app_id'=>$app['appid'],
                ['commission_rate','>=',8000],
            ];
            $acceptedTaskLists = OceanengineAcceptedTaskListModel::getInstance()->getWhere($where)
                ->orderBy('expiration_time','asc')
                ->get();
            $taskMap = array_column($acceptedTaskLists->toArray(),null,'demand_id');
            $novelDatas = NovelSpreadModel::getInstance()->getWhere(['app_id'=>$app['appid'],'spread_type'=>1,'isdel'=>0])->get();

            $taskIds = [];
            foreach($novelDatas as $novel){
                //截止投稿时间到了，就下架该小说
                if(isset($taskMap[$novel['task_id']]) && $taskMap[$novel['task_id']]['challenge_status']>6){
                    $novel->task_status = 3;
                    $novel->save();
                }
                $taskIds[] = $novel['task_id'];
            }

            foreach ($acceptedTaskLists as $task){
                if(in_array($task['demand_id'],$taskIds)){
                    continue;
                }

                //插入为存在的小说任务
                $this->insertCommonData($app,$task);
            }
        }

        return ['success'];
    }

    protected function getNotAcceptedTaskList()
    {
        $page=1;
        while (true){
            $data = Oceanengine::getInstance()->getNotAcceptedTaskList($page);

            foreach ($data['data'] as $val){
                if(!empty($val['commission_rate'])){
                    $val['app_id'] = $val['small_app_info']['app_id'];
                    $val['app_name'] = $val['small_app_info']['app_name'];
                    $this->autoCreateTableAndInsertData(
                        [
                            'table'         => 'video_oceanengine_notaccepted_task_list',
                            'keyid'         => 'id',
                            'attributes'    => $val,
                            'update_fields' => ['demand_id'],
                        ]
                    );
                }
            }

            if(empty($data['page_info']['has_more'])){
                //var_dump($data);
                break;
            }

            $page++;
            //break;
            usleep(500000);
        }

        return true;
    }

    protected function getAcceptedTaskList()
    {
        $page = 1;
        while (true) {
            $data = Oceanengine::getInstance()->getAcceptedTaskList($page);

            foreach ($data['data'] as $val) {
                if (!empty($val['commission_rate'])) {
                    $val['app_id']   = $val['small_app_info']['app_id'];
                    $val['app_name'] = $val['small_app_info']['app_name'];
                    $this->autoCreateTableAndInsertData(
                        [
                            'table'         => 'video_oceanengine_accepted_task_list',
                            'keyid'         => 'id',
                            'attributes'    => $val,
                            'update_fields' => ['demand_id'],
                        ]
                    );
                }
            }

            if (empty($data['page_info']['has_more'])) {
                //var_dump($data);
                break;
            }

            $page++;
            //break;
            usleep(500000);
        }

        return true;
    }

    protected function acceptedTask($app)
    {
        //未参与任务列表
        $where = [
            'app_id'=>$app['appid'],
            ['commission_rate','>=',8000],
        ];
        $notAccptedTaskList = OceanengineNotacceptedTaskListModel::getInstance()->getWhere($where)
            ->orderBy('expiration_time','asc')
            ->get();

        //参与任务列表
        $where = [
            'app_id'=>$app['appid'],
            ['commission_rate','>=',8000],
        ];
        $accptedTaskIds = OceanengineAcceptedTaskListModel::getInstance()->getWhere($where)
            ->orderBy('expiration_time','asc')
            ->pluck('demand_id')
            ->toArray();

        //todo 1 开始接受任务
        foreach ($notAccptedTaskList as $task){
            if(in_array($task['demand_id'],$accptedTaskIds)){
                continue;
            }

            if($task['commission_rate']<8000){
                continue;
            }

            try{
                Oceanengine::getInstance()->acceptedTask($task);
            }catch (\Throwable $e){}

            //测试阶段，只接受一个跳出
            //break;

            usleep(500000);
        }

        return true;
    }

    /**
     *  插入通用任务数据，只有任务数据情况下插入
     * @param $businessData
     * @param $task
     * @return int
     * @throws \app\exception\IndexException
     */
    protected function insertCommonData($businessData,$task)
    {
        $mainImage = $task['demand_icon'];
        $mainImageFileName = substr(md5(uniqid().time()),-26).'.png';
        try{
            $res = TencentCos::getInstance()->uploadLocalFile($mainImage,'oceanengine/novel',$mainImageFileName);
            if(isset($res['Location'])){
                $mainImage = 'https://'.$res['Location'];
            }
        }catch (\Exception $e){}

        $task['demand_name'] = str_replace([$businessData['fix_name']],'',$task['demand_name']);

        //判断投稿截止时间，是否上架还是下架
        if($task['challenge_status']>6){
            $task['task_status'] = 3;
        }else{
            $task['task_status'] = 2;
        }

        $insert = [
            'title'=>$task['demand_name'],
            'main_image'=>$mainImage,
            'desc'=>'',
            'platform'=>$businessData['platform'],
            'business_id'=>$businessData['business_id'],
            'data_source_key'=>OceanengineAcceptedTaskListModel::getInstance()->getTable(),
            'data_source_id'=>$task['id'],
            'episode_num'=>'0',
            'is_end'=>0,
            'start_time'=>$task['create_time'],
            'labels'=>'',
            'status'=>0,

            'app_id'=>$task['app_id'],
            'task_id'=>$task['demand_id'],
            'task_start_time'=>$task['expiration_time'],
            'task_end_time'=>$task['expiration_time_end'],
            'task_settle_type'=>$task['pay_type'],
            'payment_allocate_ratio'=>$task['commission_rate'],
            'task_status'=>$task['task_status'],
            'task_refund_period'=>$task['account_divide_day']??7,
        ];

        return NovelSpreadModel::getInstance()->saveData($insert);
    }

    public function getTalentVideoIncomeData()
    {
        //todo 1 获取小说任务id
        $where = [
            'data_source_key'=>OceanengineAcceptedTaskListModel::getInstance()->getTable(),
            'isdel'=>0,
            'spread_type'=>1,
        ];
        $taskIds = NovelSpreadModel::getInstance()->getWhere($where)->pluck('task_id')->toArray();

        //todo 2 获取投后数据信息并插入更新数据，天为单位
        foreach($taskIds as $taskId){
            $page=1;
            while (true){
                $data = Oceanengine::getInstance()->getTalentVideoIncomeData($taskId, $page);

                foreach ($data['data'] as $val){
                    if(!empty($val['item_info_daily_list'])){
                        foreach($val['item_info_daily_list'] as $v){
                            $row = $val;
                            foreach ($v as $kk=>$vv){
                                $row['day_'.$kk] = $vv;
                            }
                            unset($row['item_info_daily_list']);

                            $this->autoCreateTableAndInsertData(
                                [
                                    'table'         => 'video_oceanengine_talent_video_income_list',
                                    'keyid'         => 'id',
                                    'attributes'    => $row,
                                    'update_fields' => ['demand_id','item_id','author_id','day_p_date'],
                                ]
                            );
                        }
                    }
                }

                if(empty($data['page_info']['has_more'])){
                    //var_dump($data);
                    break;
                }

                $page++;
                //break;
                usleep(500000);
            }
        }


        return ['success'];
    }
}